package com.jiangyao.common.configs;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.List;

/**
 * SwaggerConfiguration
 *
 * @author yangyongchuan
 * @since 2020-07-19
 */
@Configuration
public class SwaggerConfiguration {

	/**
	 * 是否开启swagger，生产环境一般关闭，所以这里定义一个变量
	 */
	@Value("${swagger.enabled}")
	private Boolean enable;

	/**
	 * 项目应用名
	 */
	@Value("${swagger.api.name}")
	private String apiName;

	/**
	 * 项目版本信息
	 */
	@Value("${swagger.api.version}")
	private String apiVersion;

	/**
	 * 访问地址
	 */
	@Value("${swagger.api.serviceUrl}")
	private String apiServiceUrl;

	/**
	 * 项目描述信息
	 */
	@Value("${swagger.api.description}")
	private String apiDescription;

	/**
	 * api联系信息-姓名
	 */
	@Value("${swagger.api.contact.name}")
	private String apiContactName;

	/**
	 * api联系信息-地址
	 */
	@Value("${swagger.api.contact.url}")
	private String apiContactUrl;

	/**
	 * api联系信息-邮箱
	 */
	@Value("${swagger.api.contact.email}")
	private String apiContactEmail;


	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title(apiName).description(apiDescription).version(apiVersion)
				//.termsOfServiceUrl(apiUrl).contact(new Contact(apiContactName, apiContactUrl, apiContactEmail))
				.build();
	}

	@Bean
	public Docket createRestApi() {
		List<SecurityScheme> securitySchemes = new ArrayList<>();
		List<RequestParameter> globalRequestParameters = new ArrayList<>();
		RequestParameterBuilder requestParameterBuilder = new RequestParameterBuilder();
		globalRequestParameters.add(requestParameterBuilder.name("token").description("登录凭证").in(ParameterType.HEADER).build());

		securitySchemes.add(new ApiKey("token", "token", "登录凭证", null));
		return new Docket(DocumentationType.SWAGGER_2).pathMapping("/")
				// 定义是否开启swagger，false为关闭，可以通过变量控制
				.enable(enable)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//				.apis(RequestHandlerSelectors.basePackage("com.jiangyao.controller"))
				.paths(PathSelectors.any())
				.build().useDefaultResponseMessages(false)
				.host(apiServiceUrl)
				.globalRequestParameters(globalRequestParameters).securitySchemes(securitySchemes);
	}
}